﻿@model IEnumerable<Citi.Scheduler.WebUi.Models.RoutineModel>
@{
    ViewBag.Title = "Calendar";
}
<script type="text/javascript">

    var loading = false;
    var firstTime = false;
    var month = 0;
    var year = 0;
    
    $(document).ready(function () {
        month = new Date().getMonth() + 1;
        year = new Date().getFullYear();
        firstTime = true;
        setCalendar();
        firstTime = false;
    });

    function setCalendar() {
        $('#calendar').fullCalendar('destroy');
        loading = true;

        $('#calendar').fullCalendar({
            theme: true,
            allDaySlot: false,
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,agendaWeek,agendaDay'
            },
            cache: false,
            eventClick: function(calEvent, jsEvent, view) {
                if (calEvent.status == 'Scheduled') {
                    $("#executionHistory")[0].innerHTML = '';
                    return;
                }

                fillExecutionData(calEvent.id);

//                $.ajax({
//                    url: '@Url.Action("IndexJson", "RoutineExecutionHistory")?showErrors=true&routineExecutionId=' + calEvent.id,
//                    dataType: 'json',
//                    success: function (doc) {
//                        //$("#executionHistory").html(doc.html);
//                        $("#executionHistory")[0].innerHTML = doc.html;
//                        generateMemoryUsageChart(doc);
//                    }
//                });
            },
            editable: true,
            events: function (start, end, callback) {
                var month = eval(start.getMonth() + 1);
                var year = start.getFullYear();
                if (start.getDate() != 1) month++;

                if (month > 12) {
                    month = 1;
                    year++;
                }

                $.ajax({
                    url: '@Url.Action("FillCalendar")?month=' + month + '&year=' + year + '&routineId=' + @ViewBag.RoutineId + '&categoryId=' + @ViewBag.CategoryId,
                    dataType: 'json',
                    success: function (doc) {
                        var events = [];
                        $(doc).each(function () {
                            events.push({
                                title: $(this).attr('title'),
                                start: $(this).attr('start'),
                                id: $(this).attr('id'),
                                status: $(this).attr('status'),
                                end: $(this).attr('end'),
                                color: $(this).attr('color')
                            });
                        });
                        callback(events);
                    }
                });
            },
            eventRender: function (event, element, calEvent) {
                element.find(".fc-event-title").before($("<span class=\"fc-event-icons\"></span>").html("<img src='@Url.Content("~/Content/Images/RoutineStatus")/" + event.status + ".png' style='width:12px;' />&nbsp;"));
            },
            viewDisplay: function(view) {
                $("#periodSummary")[0].innerHTML='';
                var params = {
                     routineId: @ViewBag.RoutineId, 
                     categoryId: @ViewBag.CategoryId, 
                     start: dateFormat( view.start, "mm/dd/yyyy HH:MM:ss"), 
                     end: dateFormat( view.end, "mm/dd/yyyy HH:MM:ss")
                };
                
                $.ajax({
                    url: '@Url.Action("PeriodSummary", "RoutineExecution")',
                    data: params,
                    dataType: 'json',
                    success: function (doc) {
                        @if (ViewBag.CategoryId == null || ViewBag.CategoryId == 0)
                        {
                            <text>$("#periodSummary")[0].innerHTML= doc.html;</text>
                        }

                        if (doc.noData == false){
                            generateExecutionChart(doc);
                            generateStatusChart(doc);
                        }
                        else{
                            $("#periodSummaryChart")[0].innerHTML = "There's no information for the selected date";   
                            $("#periodSummaryStatusChart")[0].innerHTML = "";
                        }
                    }
                });            
            }
        });

        loading = false;
    }

    function generateExecutionChart(json)
    {
        var chart = new Highcharts.Chart({
            chart: { renderTo:'periodSummaryChart', className: 'chart', defaultSeriesType: 'line', marginBottom: 25, marginRight: 130 }, 
		    legend: { align: 'right', borderWidth: 0, layout: 'vertical', verticalAlign: 'top', x: -10, y: 100 }, 
		    subtitle: { text: json.period },
		    title: { text: 'Evolution runtime', x: -20 }, 
		    tooltip: { formatter: function() { return '<b>'+ this.x +'</b><br/>'+ this.y + ' minutes'; } } ,
		    xAxis: { categories: json.categories },
//             xAxis: {
//                type: 'datetime',
//                dateTimeLabelFormats: { // don't display the dummy year
//                    month: '%e. %b',
//                    year: '%b'
//                }
//            },

		    yAxis: { plotLines: [{ color: '#808080', value: 0, width: 1 }], title: { text: 'Total Time (minutes)' } },
            credits: { enabled: false}
        });   

        $.each(json.series, function (itemNo, item) {
            chart.addSeries({                        
                name: item.Name,
                data: item.Data
            }, false);
        });
                        
        chart.redraw();
    }

    function generateStatusChart(json)
    {
        var chart = new Highcharts.Chart({
            chart: { type: 'column', renderTo:'periodSummaryStatusChart' },
            title: { text: 'Status' },
            subtitle: { text: json.period },
            xAxis: { categories: [''] },            
            yAxis: { min: 0, title: { text: 'Number of Occurences' } },
            credits: { enabled: false},
            tooltip: {
                headerFormat: '<span style="font-size:12px"><b>Status</b></span><table>',
                pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
                    '<td style="padding:0"><b>{point.y} occurences</b></td></tr>',
                footerFormat: '</table>',
                shared: true,
                useHTML: true
            },
            plotOptions: { column: { pointPadding: 0.2, borderWidth: 0 } }
        });

        $.each(json.errorsSeries, function (itemNo, item) {
            chart.addSeries({                        
                name: item.Name,
                data: item.Data,
                color: item.ColorHexadecimal
            }, false);
        });
                        
        chart.redraw();
    }
</script>
@if (ViewBag.RoutineId != 0)
{
    <h2>
        Routine @ViewBag.Name</h2>
}
else
{
    <h2>
        Category @ViewBag.Name</h2>
}
<div id="periodSummary">
</div>
<div id="periodSummaryChart">
</div>
<div id="periodSummaryStatusChart">
</div>
<div id="calendar">
</div>
@Html.Partial("~/Views/RoutineExecution/ExecutionResult.cshtml");
@*<div id="executionHistory">
</div>
<div id="executionError">
</div>
<div id="memoryUsageChart">
</div>*@
@*@Html.Action("Teste", "RoutineExecution")*@